package net.huashitong.supervision.task.service;

import com.sirdc.modules.sys.entity.SysLogin;
import com.sirdc.modules.sys.entity.SysUser;
import com.sirdc.modules.sys.filter.SysUserFilter;
import com.sirdc.modules.sys.service.SysLoginService;
import com.sirdc.modules.sys.service.SysUserService;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.supervision.task.entity.*;
import net.huashitong.supervision.task.filter.SpecialTaskFilter;
import net.huashitong.supervision.task.filter.TaskUnitFilter;
import net.huashitong.supervision.task.util.WeekDayUtil;
import net.huashitong.synthetical.newSupervision.util.HolidayUtils;
import net.huashitong.util.DateUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 * User: ling
 * Date: 2019/7/22
 * Time: 20:14
 * To change this template use File | Settings | File Templates.
 * Description:定时调度任务,自动生成多时限的单位任务
 * 规则：
 *
 */

@Service
public class TaskUnitScheduleService {
    @Lazy
    @Autowired
    private TaskMainService taskMainService;
    @Autowired
    private TaskUnitService taskUnitService;
    @Autowired
    private TimeLimitService timeLimitService;
    @Autowired
    private TaskSubService taskSubService;
    @Autowired
    private SysUserService userService;
    @Autowired
    private SysLoginService sysLoginService;
    @Autowired
    private TaskUserService taskUserService;
    @Autowired
    private SMSUtilService smsUtilService;
    @Autowired
    private SpecialTaskService specialTaskService;
    @Autowired
    private TaskEndDateService taskEndDateService;

    //定时查询是否有多时限的单位任务需要生成
    @Transactional
    public void taskUnitTimes() throws ParseException {
        //查询任务时限表所有未结束的数据
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String timeNow = dateFormat.format(Calendar.getInstance().getTime());
        System.out.println("当前的日期： " + timeNow);
        //取出当前天是几号
        //当前时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        //当前日
        int nowYear = calendar.get(Calendar.YEAR);//年
        int nowMonth = calendar.get(Calendar.MONTH) + 1;//月
        int day = calendar.get(Calendar.DAY_OF_MONTH);//日
        String yearStr = "";
        String monthStr = nowMonth + "";
        String dayStr = day + "";
        if (nowMonth < 10) {
            monthStr = 0 + monthStr;
        }
        if (day < 10) {
            dayStr = 0 + dayStr;
        }
        //未结束的项目
        List<TimeLimit> timeLimits = timeLimitService.queryState("1");
        if (ObjectUtils.isNotBlank(timeLimits)) {
            for (TimeLimit timeLimit : timeLimits) {
                String timeType = timeLimit.getTimeType();
                /*
                 * 特殊任务多时限生成;
                 * */

                //判断是否有特殊任务时限
                TaskSub taskSub = null;
                SpecialTask specialTask = null;
                if (StringUtils.isNotBlank(timeLimit.getSpecialTaskId())) {
                    //查询最新特殊任务
                    // ----- 比如重大立项-----
                     specialTask = specialTaskService.getById(timeLimit.getSpecialTaskId());
                     if(ObjectUtils.isBlank(specialTask)){
                         continue;
                     }
                    String timeRound = specialTask.getTimeRound();//轮次
                    String dueDate = specialTask.getRoundLimit();
                    if(timeNow.equals(dueDate)){
                        int times = Integer.parseInt(timeRound);
                        times =times+1;
                        if("2".equals(timeType)){
                            //周期性
                            //生成下一次提醒时间
                            String nextDate = DateUtil.nextRemindDate(dueDate, timeLimit.getPeriod(), timeLimit.getDay());

                            SpecialTask nextTask = new SpecialTask();
                            BeanUtils.copyProperties(specialTask,nextTask);
                            nextTask.setRoundLimit(nextDate);
                            nextTask.setTimeRound(times+"");
                            nextTask.setType("0");
                            nextTask.setStatus("1");
                            nextTask.setSysId(null);
                            nextTask.setEvaluations(null);
                            nextTask.setOverdueDay(null);

                            specialTaskService.save(nextTask,specialTask.getCreateUser());


                            //
                            timeLimit.setState("0");//结束
                            timeLimitService.update(timeLimit
                            );
                            //生成吓一条
                            TimeLimit  tl = new TimeLimit();
                            BeanUtils.copyProperties(timeLimit,tl);
                            tl.setSysId(null);
                            tl.setState("1");
                            tl.setTimeLimit(nextDate);
                            timeLimitService.save(tl,timeLimit.getCreateUser());



                        }else if("3".equals(timeType))
                        {
                            String multitimes = timeLimit.getTimeLimits();
                            String[] split = multitimes.split(",");
                            String remindDate = DateUtil.nextDateByMultiTime(split, dueDate);
                            SpecialTask nextTask = new SpecialTask();
                            BeanUtils.copyProperties(specialTask,nextTask);
                            nextTask.setRoundLimit(remindDate);
                            nextTask.setTimeRound(times+"");
                            nextTask.setType("0");
                            nextTask.setStatus("1");
                            nextTask.setSysId(null);
                            nextTask.setEvaluations(null);
                            nextTask.setOverdueDay(null);

                            specialTaskService.save(nextTask,specialTask.getCreateUser());
                            timeLimit.setState("0");
                            timeLimitService.update(timeLimit);

                            TimeLimit  tl = new TimeLimit();
                            BeanUtils.copyProperties(timeLimit,tl);
                            tl.setSysId(null);
                            tl.setState("1");
                            tl.setTimeLimit(remindDate);
                            timeLimitService.save(tl,timeLimit.getCreateUser());

                        }
                    }


                    ///---end  重大立项判断  ---
                } else if (StringUtils.isNotBlank(timeLimit.getTaskSubId())) {
                    taskSub = taskSubService.getById(timeLimit.getTaskSubId());
                }
                if (ObjectUtils.isNotBlank(taskSub)) {
                    //查询当前任务
                    TaskMain taskMain = taskMainService.getById(taskSub.getTaskMainId());
                    //查询当前的第一轮单位任务
                    //List<TaskUnit> taskUnits = taskUnitService.getBySubId(timeLimit.getTaskSubId());
                    //查询所有子任务
                    TaskUnitFilter unfilter = new TaskUnitFilter();
                    unfilter.setTaskSubId(timeLimit.getTaskSubId());
                    List<TaskUnit> taskUnits = taskUnitService.queryFilter(unfilter);
                    /**
                     * 找出需要继续循环的任务 0 需要循环， 1 不要循环，如果某个任务被终止任务 吧cycflag 改成1 即可
                     */
                    taskUnits=taskUnits.stream().filter(taskUnit -> taskUnit.getCycflag()==0).collect(Collectors.toList());
                    if (ObjectUtils.isBlank(taskUnits)) {
                        continue;
                    }

                    if("2".equals(timeType))
                    {
                        for (TaskUnit taskUnit : taskUnits) {

                            String dueDate = taskUnit.getTimeLimit();
                            if(!timeNow.equals(dueDate))
                            {
                                continue;
                            }
                            String taskunitId = taskUnit.getSysId();
                            int t = taskEndDateService.isOverdue(taskMain.getSysId());
                            if(t<=0){
                                taskUnit.setCycflag(1);
                                taskUnitService.update(taskUnit);

                                continue;
                            }


                            String nextDate = DateUtil.nextRemindDate(dueDate, taskUnit.getPeriod(), taskUnit.getDay());
                            String tr = taskUnit.getTimeRound();
                            int timeRound = Integer.parseInt(tr);
                            timeRound= timeRound+1;

                            TaskUnit newTaskUnit = setNewTask(taskUnit, nextDate, timeRound + "");
                            taskMain.setTimeLimit(newTaskUnit.getTimeLimit());
                            taskMainService.update(taskMain);


                        }


                    }
                    //判断任务时限类
                    else if ("3".equals(timeLimit.getTimeType())) {

                        //判断是否有多时限
                        String limits = timeLimit.getTimeLimits();

                        String[] dates = limits.split(",");

                        for (TaskUnit taskUnitOld : taskUnits) {
                            if(!timeNow.equals(taskUnitOld.getTimeLimit())){
                                continue;
                            }

                            String limitDate = taskUnitOld.getTimeLimit();
                            String nextDate = DateUtil.nextDateByMultiTime(dates, limitDate);
                            List<TaskUser> taskUsers = taskUserService.getByTaskUnitId(taskUnitOld.getSysId());
                            //创建一个内容相同的单位任务
                            TaskUnit newTaskUnit = new TaskUnit();
                            BeanUtils.copyProperties(taskUnitOld, newTaskUnit);
                            newTaskUnit.setSysId(null);
                            newTaskUnit.setOverdueDay(null);
                            newTaskUnit.setTimeLimit(nextDate);
                            newTaskUnit.setScore(null);
                            newTaskUnit.setStatus("2");
                            if (ObjectUtils.isNotBlank(taskUsers)) {
                                newTaskUnit.setType("1");//已批转
                                newTaskUnit.setState("1");//已办
                            } else {
                                newTaskUnit.setType("0");//待签收
                                newTaskUnit.setState("0");//待办
                            }
                            String timeRound = taskUnitOld.getTimeRound();
                            int i1 = Integer.parseInt(timeRound);
                            newTaskUnit.setTimeRound((i1 + 1)+ "");
                            taskUnitService.saveUnit(newTaskUnit);
                            taskUnitOld.setCycflag(1);// 1执行过循环，0 未执行过定时任务；
                            taskUnitService.update(taskUnitOld);

                            //发送短信。查询当前单位的领导
                            SysUserFilter userFilter = new SysUserFilter();
                            userFilter.setRoleId("02");
                            userFilter.setDeptId(taskUnitOld.getDeptId());
                            List<SysLogin> loginList = sysLoginService.queryUserLoginByRoleDept(userFilter);
                            for (SysLogin sysLogin : loginList) {
                                SysUser sysUser = userService.getById(sysLogin.getSysId());
                                String mobile = sysUser.getMobile();
                                if (StringUtils.isNotBlank(mobile)) {
                                    smsUtilService.taskNewSmsService(taskUnitOld, sysUser);
                                }
                            }
                            taskMain.setTimeLimit(newTaskUnit.getTimeLimit());


                        }

                    }
                    taskMainService.update(taskMain);
                }
            }
        }
    }

    /**
     * 设置新任务
     * @param taskUnit
     * @param nextDate
     * @param timeRound
     */
    private TaskUnit setNewTask(TaskUnit taskUnit,String nextDate,String timeRound){
        List<TaskUser> taskUsers = taskUserService.getByTaskUnitId(taskUnit.getSysId());
        TaskUnit newTaskUnit = new TaskUnit();
        BeanUtils.copyProperties(taskUnit, newTaskUnit);
        newTaskUnit.setSysId(null);
        newTaskUnit.setOverdueDay(null);
        newTaskUnit.setTimeLimit(nextDate);
        newTaskUnit.setScore(null);
        newTaskUnit.setStatus("2");

        if (ObjectUtils.isNotBlank(taskUsers)) {
            newTaskUnit.setType("1");//已批转
            newTaskUnit.setState("1");//已办
        } else {
            newTaskUnit.setType("0");//待签收
            newTaskUnit.setState("0");//待办
        }
        newTaskUnit.setTimeRound(timeRound+"");
        taskUnitService.saveUnit(newTaskUnit);
        //设置自动循环状态已经走过，下次定时任务不走这条了
        taskUnit.setCycflag(1);
        taskUnitService.update(taskUnit);
        //创建人员任务
        createTaskUser(taskUsers, newTaskUnit);

        //发送短信。查询当前单位的领导
        SysUserFilter userFilter = new SysUserFilter();
        userFilter.setRoleId("02");
        userFilter.setDeptId(taskUnit.getDeptId());
        List<SysLogin> loginList = sysLoginService.queryUserLoginByRoleDept(userFilter);
        for (SysLogin sysLogin : loginList) {
            SysUser sysUser = userService.getById(sysLogin.getSysId());
            String mobile = sysUser.getMobile();
            if (StringUtils.isNotBlank(mobile)) {
                smsUtilService.taskNewSmsService(taskUnit, sysUser);
            }
        }

        return newTaskUnit;
    }


    /**
     * 查询上一轮单位任务批转过没有
     *
     * @param taskUnitList
     * @return
     */
    public String createTaskUser(List<TaskUser> taskUnitList, TaskUnit taskUnit) {

        //查询上一轮单位任务批转的用户
        List<String> users = new ArrayList<>();
        if(ObjectUtils.isBlank(taskUnitList))
        {
            return "200";
        }
        String sysId = taskUnitList.get(0).getSysId();
        List<TaskUser> taskUsers = taskUserService.getByTaskUnitId(sysId);
        if (ObjectUtils.isNotBlank(taskUsers)) {
            for (TaskUser taskUser : taskUsers) {
                String userId = taskUser.getUnitUserId();
                String mobile = userService.getById(userId).getMobile();
                TaskUser newTaskUser = new TaskUser();
                BeanUtils.copyProperties(taskUser, newTaskUser);
                taskUser.setTaskUnitId(taskUnit.getSysId());
                SysLogin login = sysLoginService.getById(userId);
                if ("03".equals(login.getRoleId())) {
                    //分管， 判断他是否批转过
                    List<TaskUser> taskUnit2 = taskUserService.getByCreateUserAndTaskUnitId(userId, taskUnitList.get(0).getSysId());
                    if (ObjectUtils.isNotBlank(taskUnit2)) {
                        //批转过，状态改为一批转
                        taskUser.setStatus("1");
                        taskUser.setState("1");//已办
                    } else {
                        taskUser.setStatus("0");//未处理
                        taskUser.setState("0");//待办
                    }
                } else {
                    //经办
                    taskUser.setStatus("0");//未处理
                    taskUser.setState("0");//待办
                }
                users.add(userId);
                taskUserService.saveTaskUser(taskUser);
                //发送批转短信
                smsUtilService.taskUserSMS(taskUnit, userService.getById(userId));
            }
            return "200";
        } else {
            return "500";
        }
    }
}
